package club.xinghe.filter;

import club.xinghe.entity.Teacher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 过滤器说明:过滤掉没有登录的老师
 *
 * @姚文斌
 * @create 2019-10-09 上午 10:36
 */
@WebFilter("/teacher/*")//过滤范围
public class TeacherNoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //编写过滤业务
        System.out.println("进入了'教师'未登录过滤器！");
        //将 servletRequest和servletResponse对象转为request对象和reponse对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //得到session域里的student对象
        HttpSession session = request.getSession();
        Teacher teacher = (Teacher) session.getAttribute("teacher");
        if (teacher!=null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{response.sendRedirect("/login.html");}
    }

    @Override
    public void destroy() {

    }
}
